<%@ page import="com.macrosolution.exdebito.Message" %>
<script src="${resource(dir: 'site/js/plugin/bootstrap-timepicker', file: 'bootstrap-timepicker.min.js')}"></script>
<link rel="stylesheet" href="${resource(dir: 'site/css', file: 'bootstrap-datetimepicker.min.css')}" type="text/css">
<style type="text/css">
.bootstrap-timepicker-widget  
{
    z-index:100002 !important;
    position:absolute;
}

<%--.modal-dialog {--%>
<%--  width: 807px;--%>
<%--  margin: 30px auto;}--%>
</style>

<script type="text/javascript">

$(document).ready(function(){
	$('#tree_root').hide();
	
	var date = new Date();
	var dateVal = $.datepicker.formatDate('dd/mm/yy', date);
	$('#dStart').val(dateVal);
	$('#dEnd').val(dateVal);

	
	
	
	var dateStart =$("#start-datepicker").datepicker({
		startDate:dateVal,
	  	autoclose:"true", 
		format:"dd/mm/yyyy",
		todayHighlight:'true',
		beforeShow: function() {

			 	
				var $datePicker = $("#start-datepicker");
				$datePicker.css("z-index", 100000);
		      
		   }
		
	});
		
		dateStart.on('changeDate', function(e){
			var date = $(this).datepicker('getDate');
			
			var dateVal = $.datepicker.formatDate('dd/mm/yy', date);
				$('#dStart').val(dateVal);
				$('#dStart').change();
				$('#dEnd').val(dateVal);
				
				$("#end-datepicker").datepicker("setStartDate",dateVal);
				$('#dEnd').change();
		});

		var dateEnd =$("#end-datepicker").datepicker({

			startDate:dateVal,
		  	autoclose:"true", 
			format:"dd/mm/yyyy",
			todayHighlight:'true',
			beforeShow: function() {

			 	
				var $datePicker = $("#end-datepicker");
				$datePicker.css("z-index", 100000);
		      
		   }
		});
			dateEnd.on('changeDate', function(e){
			var date = $(this).datepicker('getDate');
			
			var dateVal = $.datepicker.formatDate('dd/mm/yy', date);
				$('#dEnd').val(dateVal);
				$('#dEnd').change();
			});	
			
	createTree(${usr.id});
	setTimeout(function() {
		createFaterData(${usr.id},'currentUserTree');
	}, 1000)
	
		
	
	 var sH = $('#startH').timepicker({

		minuteStep: 1,
        secondStep: 5,
        showInputs: false,
        showSeconds: false,
        showMeridian: false
        
	}).on('changeTime.timepicker', function(e) {
		
		

			    
	  })
	
	var eH = $('#endH').timepicker({

		minuteStep: 1,
        secondStep: 5,
        showInputs: false,
        showSeconds: false,
        showMeridian: false


	});


	 setTimeout(showTree, 2000);
	 	
});





	function createFaterData(usrID,childElem){
			
		${remoteFunction(
				asynchronous:false,
				controller:'user',
				action:'get_parent_json',
				onSuccess:'createFaterTree(data,childElem,usrID)',
				params: '\'userId=\'+usrID')}
		
	}

	function createFaterTree(data,childElem,childID){
		
		if(data && data!='' && childID!=data.id){
			
		var  iddi = "subjects_"+data.id;
		var ulObj = document.createElement("ul");
		ulObj.setAttribute("id",iddi);
		var leave = '<li  id="user_'+data.id+'" ><span  id="span_'+data.id+'"><i class="fa fa-lg fa-user">'+' '+'<input type="checkbox" name="eventUserId" value="'+data.id+'"></i><b id="name_'+data.id+'">...caricando...</b></span></li>'
		$(ulObj).html(leave);
		var child =$("#"+childElem);
		
		$('#tree_root').html(ulObj);
		$('#span_'+data.id).after(child);
		}
		if(data.owner){
			createFaterData(data.id,iddi);
		}else{
			retrieveRoleNameTree(data);
		}
		
	}
	

function createTree(usrId){
	${remoteFunction(
			asynchronous:false,
			controller:'message',
			action:'get_current_leave',
			onSuccess:'build_leave(data,"currentUserTree")',
			params: '\'id=\'+usrId'
			
		)}
	 var span = "span_"+usrId;
	${remoteFunction(
		asynchronous:false,
		controller:'user',
		action:'get_user_json',
		onSuccess:'createTreeUsers(data,textStatus,span);',
		params: '\'userId=\'+usrId'
		
		
	)}

	
	
	
	
}
var cicling=0;
function createTreeUsers(data,textStatus,idPadre){
	if(idPadre=='currentUserTree'){
		cicling=1;
		}

	if(data.subjects){
		if(cicling<2){
			cicling++;
			}
		
		var  iddi = "subjects_"+data.id;
		var ulObj = document.createElement("ul");
		ulObj.setAttribute("id",iddi);
		
		
		$("#"+idPadre).after(ulObj);
		
		for(var ix=0; ix<data.subjects.length;ix++){
			var id_leave=data.subjects[ix].id;
			var closed='';
			if(cicling==2){
				closed='user_closed';
				
			}
			var leave = '<li  id="user_'+id_leave+'" ><span class="'+closed+'" id="span_'+id_leave+'"><i class="fa fa-lg fa-user">'+' '+'<input type="checkbox" class="parentCheckBox" name="eventUserId" value="'+id_leave+'"></i><b id="name_'+id_leave+'">...caricando...</b></span></li>'
			build_leave(leave,iddi);
			var spanId = "span_"+data.subjects[ix].id;			
			createTreeUsers(data.subjects[ix],textStatus,spanId);
		}
	}
}	

function retrieveRoleNameTree(json){
	
	if(json && json.id){
		
	${remoteFunction(
			controller:'message',
			action:'get_role_name',
			onSuccess:'addName(data);',
			params: '\'id=\'+json.id'
			
		)}
	}
	retrieveRoleNameSubjectsTree(json);
}

function retrieveRoleNameSubjectsTree(json){
	if(json.subjects){
		for(var ix=0; ix<json.subjects.length;ix++){
			
						${remoteFunction(
								controller:'message',
								action:'get_role_name',
								onSuccess:'addName(data);',
								params: '\'id=\'+json.subjects[ix].id'
								
							)}
						retrieveRoleNameSubjectsTree(json.subjects[ix]);
		}
	}
	
}

function showTree(){
	
	$('.tree > ul').attr('role', 'tree').find('ul').attr('role', 'group');
	$('.tree').find('li:has(ul)').addClass('parent_li').attr('role', 'treeitem').find(' > span').attr('title', 'Collapse this branch').on('click', function(e) {
		
		var children = $(this).parent('li.parent_li').find(' > ul > li');
		if (children.is(':visible')) {
			children.hide('fast');
			$(this).attr('title', 'Expand this branch').find(' > i').removeClass().addClass('fa fa-lg fa-plus-circle');
		} else {
			children.show('fast');
			$(this).attr('title', 'Collapse this branch').find(' > i').removeClass().addClass('fa fa-lg fa-minus-circle');
		}
		e.stopPropagation();
	});		
	
	$('#loader').hide();
	$('#tree_root').show();
	$('.user_closed').each(function(index, item){
		
		item.click();     
	});

	
	}	
		
function addName(data){
	var container='name_'+data.id	
	
	$("#"+container).html(data.text)
}


function build_leave(data,idParent){
	
	$("#"+idParent).append(data);
	
	
}



</script>

<div class="modal fade bs-example-modal-lg" id="add_message" tabindex="-1" role="dialog" aria-labelledby="wsw" aria-hidden="true">
	
	<div class="modal-dialog modal-lg">
		
		<div class="modal-content">
			
			<div class="modal-header">
        		<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        		<h4 class="modal-title" id="myModalLabel">Aggiungi un Evento </h4>
      		</div>
      		
      		<div class="modal-body">
      		<form action="save" id="messageForm" controller="message" class="form-horizontal" role="form" >
      		<div class="row">
      			<g:hiddenField name="eventUserId" value="${usr.id}"/>
      			<div class="col col-md-6">
      				
      				<g:hasErrors bean="${messageInstance}">
						<div class="alert alert-danger">
							<g:renderErrors bean="${messageInstance}" as="list" />
						</div>
					</g:hasErrors>
				     <div id="error">
				      	
				     </div>
      			
      						
										<fieldset>
											<g:hiddenField type="number"  name="userID" value="${sec.loggedInUserInfo(field:"id")}" />
											<div class="form-group">
												<label>Seleziona un'icona per l'Evento</label>
												<div class="btn-group btn-group-sm btn-group-justified" data-toggle="buttons">
													<label class="btn btn-default active">
														<input type="radio" name="eventIcon"  id="icon-1" value="fa-info" checked>
														<i class="fa fa-info text-muted"></i> </label>
													<label class="btn btn-default">
														<input type="radio" name="eventIcon"  id="icon-2" value="fa-warning">
														<i class="fa fa-warning text-muted"></i> </label>
													<label class="btn btn-default">
														<input type="radio" name="eventIcon"  id="icon-3" value="fa-check">
														<i class="fa fa-check text-muted"></i> </label>
													<label class="btn btn-default">
														<input type="radio" name="eventIcon"  id="icon-4" value="fa-user">
														<i class="fa fa-user text-muted"></i> </label>
													<label class="btn btn-default">
														<input type="radio" name="eventIcon"  id="icon-5" value="fa-lock">
														<i class="fa fa-lock text-muted"></i> </label>
													<label class="btn btn-default">
														<input type="radio" name="eventIcon"  id="icon-6" value="fa-clock-o">
														<i class="fa fa-clock-o text-muted"></i> </label>
												</div>
											</div>
				
											<div class="form-group">
												
												<input type="text" class="form-control"  name="eventTitle" id="title"  maxlength="40"  placeholder="Titolo Evento">
											</div>
											<div class="form-group">
												
												<textarea placeholder="Descrizione evento..(max 300 caratteri)" class="form-control"  rows="3" maxlength="300" id="description" name="message" value="${messageInstance?.message}"></textarea>
												
											</div>
											
											<div class="form-group">
													
<%--												<g:datePicker type="date" name="expire" precision="minute"  value="${formatDate(format:'dd-MM-yyyy',date:messageInstance?.expire)}"  />--%>
												
												<div class="input-group" data-toggle="tooltip" data-placement="left" title="Data Inizio Evento">
													<span class="input-group-addon" rel="tooltip" data-placement="top" data-original-title="doodpsdo"><i class="fa  fa-calendar fa-lg fa-fw" id="start-datepicker"></i></span>
													<input
							                        	type="text" 
							                        	
														name="dStart"
														id="dStart"
														value="" 
														class="form-control input-md"
														
														
							                        />
												</div>
											</div>
											<div class="form-group">
												
<%--												<g:datePicker type="date" name="expire" precision="minute"  value="${formatDate(format:'dd-MM-yyyy',date:messageInstance?.expire)}"  />--%>
												
												<div class="input-group" data-toggle="tooltip" data-placement="left" title="Data Fine Evento">
													<span class="input-group-addon"><i class="fa  fa-calendar fa-lg fa-fw" id="end-datepicker"></i></span>
													<input
							                        	type="text" 
							                        	placeholder="Data Fine"
														name="dEnd"
														id="dEnd"
														value="" 
														class="form-control input-md"
														
														
							                        />
												</div>
											</div>
											<div class="form-group">
													
													<div class="input-group" data-toggle="tooltip" data-placement="left" title="Ora Inizio Evento">
														<input name="startHour" class="form-control timep" id="startH" type="text" placeholder="Ora Inizio">
														<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
													</div>
											</div>
											<div class="form-group" data-toggle="tooltip" data-placement="left" title="Data Inizio Evento">
													
													<div class="input-group">
														<input name="endHour" class="form-control" id="endH" type="text" placeholder="Ora fine">
														<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
													</div>
											</div>
											
											
				
											<div class="form-group">
												<label>Seleziona un colore per l'Evento</label>
												<div class="btn-group btn-group-justified btn-select-tick" data-toggle="buttons">
													<label class="btn bg-color-darken active">
														<input type="radio"  name="eventColor"  id="option1" value="bg-color-darken txt-color-white" checked>
														<i class="fa fa-check txt-color-white"></i> </label>
													<label class="btn bg-color-blue">
														<input type="radio"   name="eventColor" id="option2" value="bg-color-blue txt-color-white">
														<i class="fa fa-check txt-color-white"></i> </label>
													<label class="btn bg-color-orange">
														<input type="radio"  name="eventColor"  id="option3" value="bg-color-orange txt-color-white">
														<i class="fa fa-check txt-color-white"></i> </label>
													<label class="btn bg-color-greenLight">
														<input type="radio"  name="eventColor" id="option4" value="bg-color-greenLight txt-color-white">
														<i class="fa fa-check txt-color-white"></i> </label>
													<label class="btn bg-color-blueLight">
														<input type="radio"  name="eventColor" id="option5" value="bg-color-blueLight txt-color-white">
														<i class="fa fa-check txt-color-white"></i> </label>
													<label class="btn bg-color-red">
														<input type="radio"  name="eventColor" id="option6" value="bg-color-red txt-color-white">
														<i class="fa fa-check txt-color-white"></i> </label>
												</div>
											</div>
				
										</fieldset>
										<div class="form-actions">
											<div class="row">
												<div class="col-md-12">
												<g:submitToRemote 
														id="btn_add"
														data-loading-text="Creazione..." 
														url="[action:'create_event',controller:'message']" 
														update="[]"  
														class="btn btn-primary" 
														value="${message(code: 'default.button.create.label', default: 'Create')}" 
														onSuccess="successAddEvent(data,textStatus);loadButt('btn_add',false)"
														onFailure="failureAddEvent(XMLHttpRequest,textStatus,errorThrown);loadButt('btn_add',false)"
														onLoading="loadButt(this.id,true)"
														before="validate()"
													/>
												</div>
												
											</div>
										</div>
									
      				
      				
      				
      				
      			
      			</div>
      			
      			<div class="col col-md-6" style="max-height:500px;overflow-y: overlay;">
      				
      				<div id="loader"><i><b>Caricamento alberatura ...</b></i>
      					<div class="progress progress-sm progress-striped active">
									<div class="progress-bar bg-color-primary" role="progressbar" style="width: 100%"></div>
								</div>
      					</div>
      				<div class="tree smart-form" id="tree_root" >
      					
						<ul id="currentUserTree" >
							
						
							
						</ul>
				
				
				
					</div>
      					
      			
      			</div>
      		
      		
      		
      		
      		
      		</div>
				   
      			</form>	
      				
      		
      		</div>
		
		</div>
	
	</div>

</div>